package starpay

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay/tool"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StarpayPaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}
type Params struct {
	MerchantRef string `json:"merchant_ref"`
	Product     string `json:"product"`
	Amount      string `json:"amount"`
	Extra       extra  `json:"extra"`
}
type extra struct {
	FiatCurrency string `json:"fiat_currency"`
}

// starpay代收回调通知
func NewStarpayPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StarpayPaymentNotifyLogic {
	return &StarpayPaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StarpayPaymentNotifyLogic) StarpayPaymentNotify(req *types.StarpayPaymentNotifyReq) (resp *types.StarpayPaymentNotifyResp, err error) {
	b, _ := sonic.Marshal(req)
	// 获取  配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.StarpayCode})
	if err != nil {
		return nil, err
	}

	sign, err := tool.GenerateSignature(req.MerchantNo, req.Params, req.SignType, conf.SecretKey, req.Timestamp)

	if sign != req.Sign {
		logc.Error(l.ctx, "signature verification failed: ", sign, req.Sign)
		return nil, xerrors.ErrSignVerifyFailed
	}
	var data types.Params
	err = json.Unmarshal([]byte(req.Params), &data)
	if err != nil {
		return nil, err
	}
	// 根据订单状态处理业务逻辑
	if data.Status == 1 {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: data.MerchantRef, ReturnJson: string(b)})
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{OrderNo: data.MerchantRef})

	}
	if data.Status == 0 {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: data.MerchantRef, ReturnJson: string(b)})
	}
	return
}
